package com.ms.config.task;

import java.io.File;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;

import com.ms.client.monitor.api.pojo.MsConfig;
import com.ms.client.monitor.api.service.ApiMsConfigService;
import com.ms.msclient.MsClientResponse;
import com.system.comm.utils.FrameFileUtil;
import com.system.comm.utils.FrameSpringBeanUtil;
import com.system.comm.utils.FrameStringUtil;
import com.system.handle.model.ResponseCode;
import com.system.handle.model.ResponseFrame;

/**
 * 启动线程3分钟更新一次配置文件
 * @author yuejing
 * @date 2016年10月22日 上午9:58:59
 * @version V1.0.0
 */
public class UpdateConfigTask {

	private static final Logger LOGGER = LoggerFactory.getLogger(UpdateConfigTask.class);

	public void run(int initialDelay, int period) {
		Environment env = FrameSpringBeanUtil.getBean(Environment.class);
		String configSearchLocations = env.getProperty("spring.cloud.config.server.native.searchLocations");
		if(configSearchLocations.startsWith("classpath:")) {
			LOGGER.info("初始化 - 读取的jar文件内的配置，关闭去Monitor拉取配置信息的定时任务.");
			return;
		}
		LOGGER.info("初始化 - 去Monitor拉取配置信息的定时任务.");
		ScheduledExecutorService service = Executors.newScheduledThreadPool(20);
		//线程，每隔5秒调用一次
		Runnable runnable = new Runnable() {
			public void run() {
				updateConfig();
			}
		};
		// 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间  
		service.scheduleAtFixedRate(runnable, initialDelay, period, TimeUnit.SECONDS);
	}

	public static ResponseFrame updateConfig() {
		ResponseFrame frame = new ResponseFrame();
		Environment env = FrameSpringBeanUtil.getBean(Environment.class);
		String configSearchLocations = env.getProperty("spring.cloud.config.server.native.searchLocations");
		
		//获取要更新的配置文件
		ApiMsConfigService apiMsConfigService = FrameSpringBeanUtil.getBean(ApiMsConfigService.class);
		try {
			MsClientResponse<MsConfig> response = apiMsConfigService.findAll();
			if(ResponseCode.SUCC.getCode() == response.getCode().intValue()) {
				List<MsConfig> data = response.getBody();
				for (MsConfig mc : data) {
					String fileName = mc.getName();
					String fileString = mc.getContent();
					if (FrameStringUtil.isEmpty(fileString)) {
						continue;
					}
					//读取本地文件
					String dirPath = configSearchLocations;
					if(dirPath.startsWith("file:")) {
						dirPath = dirPath.substring(5);
					}
					String path = dirPath + File.separator + fileName;
					String orgString = FrameFileUtil.readFileString(path);
					if(FrameStringUtil.isEmpty(orgString)) {
						//新增文件
						LOGGER.info("新增配置文件[" + path + "]");
						FrameFileUtil.createDir(dirPath);
						FrameFileUtil.writeFile(fileString, new File(path));
					} else if(!fileString.trim().equals(orgString.trim())) {
						//更新内容
						LOGGER.info("更新配置文件[" + path + "]");
						FrameFileUtil.createDir(dirPath);
						FrameFileUtil.writeFile(fileString.toString(), new File(path));
					} else {
						//无需更新
					}
				}
			} else {
				LOGGER.error("请求服务端失败");
			}
			frame.setSucc();
		} catch (Exception e) {
			String message = "更新配置文件异常: " + e.getMessage();
			LOGGER.error(message);
			frame.setCode(-2);
			frame.setMessage(message);
		}
		return frame;
	}

}